<?php
include ('common/constants.php');
include ('common/db.php');
session_start();

if ((!isset($_SESSION['user_email'])) || ($_SESSION['user_email']=='')) {
  header('location: login.php');
}

function getAcceptedSeats($res_id){
  $sql = " SELECT count(seat_number) FROM `seat` WHERE seat_status='booked' AND advert_id='{$_GET['advert_id']}' AND reservation_id='". $res_id . "';";
  if($result = mysql_query($sql)){
    return mysql_result($result, 0);
  }
}

function getRemainingSeats($res_id){
  //$sql = " SELECT count(seat_number) FROM `seat` WHERE seat_status='open' AND advert_id='{$_GET['advert_id']}' AND reservation_id<>'". $res_id . "';";
  $sql = " SELECT count(seat_number) FROM `seat` WHERE seat_status='open' AND advert_id='{$_GET['advert_id']}' AND reservation_id IS NULL;";
  if($result = mysql_query($sql)){
    return mysql_result($result, 0);
  }
}

?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Carpooling - View/Edit Advertiesement</title>
<link href="resources/css/bootstrap.min.css" rel="stylesheet">
<link href="resources/css/bootstrap-responsive.min.css" rel="stylesheet">
<link href="resources/css/datepicker.css" rel="stylesheet">
<link href="resources/css/jquery.timepicker.css" rel="stylesheet">
<style type="text/css">
.cus_row {
	-moz-box-sizing: border-box;
	float:left;
	min-height: 1px;
	padding-right: 15px;
	position: relative;
}
	body {
		padding-top: 40px;
		padding-bottom: 40px;
		background-color: #f5f5f5;
	}

      .form-signin {
        max-width: 80%;
        padding: 19px 29px 29px;
        margin: 0 auto 20px;
        background-color: #fff;
        border: 1px solid #e5e5e5;
        -webkit-border-radius: 5px;
           -moz-border-radius: 5px;
                border-radius: 5px;
        -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
           -moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
                box-shadow: 0 1px 2px rgba(0,0,0,.05);
      }
      .form-signin .form-signin-heading,
      .form-signin .checkbox {
        margin-bottom: 10px;
      }
      .form-signin input[type="text"],
      .form-signin input[type="password"] {
        font-size: 16px;
        height: auto;
        margin-bottom: 15px;
        padding: 7px 9px;
      }

</style>

<script type="text/javascript" src="resources/js/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>

</head>

<body>
<div class="navbar navbar-inverse navbar-fixed-top">
  <div class="navbar-inner">
    <div class="container"> 
    
        <?php 
		
		if (!isset( $_GET )){
			echo "Nothing to save."; 
		}
		
		//create array to temporarily grab variables
		$input_arr = array();
		//grabs the $_GET variables and adds slashes
		foreach ($_GET as $key => $input_arr) {
			$_GET[$key] = addslashes(htmlspecialchars($input_arr));
		}
  
		  $sql = " SELECT a.*, (select count(seat_number) from `seat` where advert_id='{$_GET['advert_id']}') as numOfSeats FROM advertisement a, seat c WHERE a.advert_id = c.advert_id AND a.email='". $_SESSION["user_email"]. "' AND a.advert_id = '{$_GET['advert_id']}'";
		  $result = mysql_query($sql) or trigger_error(mysql_error());
      //echo $sql;
      //mysql_result($result,0,"mon");

      $vehicle_type   = mysql_result($result, 0, "vehicle_type_id");
      $numOfSeats     = mysql_result($result, 0, "numOfSeats");
		
		$travelDateFormatted = DateTime::createFromFormat('Y-m-d', mysql_result($result, 0, "travel_date"));
		?>
        
    	<a class="btn btn-navbar" style="margin-top: 25px;" data-toggle="collapse" data-target=".nav-collapse">
          <span class="icon-bar"></span> 
          <span class="icon-bar"></span> 
          <span class="icon-bar"></span> 
      	</a> <a class="brand" style="text-align:center;" href="home.php"><img src="resources/icons/share_ride.png" style="max-width:55px; padding-right:15px"/>Carpooling.lk</a>
      <div class="nav-collapse collapse">
        <ul class="nav navbar-nav">
          <li style="text-align:center; float:left">
            <a href="advertise.php"><img src="resources/icons/speaker.png" style="max-width:40px; min-width: 20px;"/><br />Advertise</a>
          </li>
          <li style="text-align:center; float:left">
          	<a href="publish.php"><img src="resources/icons/publish.png" style="max-width:40px; min-width: 20px;"/><br />Publish</a>
          </li>
          <li style="text-align:center; float:left">
          	<a href="#notifPanel" data-toggle="modal"><img src="resources/icons/notification.png" style="max-width:40px; min-width: 20px;"/><br />Notifications</a>
          </li>
          <li style="text-align:center; float:left">
          	<a href="my_posts.php"><img src="resources/icons/my_posts.png" style="max-width:40px; min-width: 20px;"/><br />My Posts</a>
          </li>
          <li style="text-align:center; float:left">
          	<a href="user_details.php"><img src="resources/icons/user_details.png" style="max-width:40px; min-width: 20px;"/><br />User Details</a>
          </li>
          <li style="text-align:center; float:left">
          	<a href="preferences.php"><img src="resources/icons/preferences.png" style="max-width:40px; min-width: 20px;"/><br />Preferences</a>
          </li>
          <li style="text-align:center; float:left">
          	<a data-toggle="collapse" data-target="#srch_panel"><img src="resources/icons/search.png" style="max-width:40px; min-width: 20px;"/><br />Search</a>
          </li>
          <li style="text-align:center; float:left; line-height: 0px; max-width: 200px;">
            &nbsp;&nbsp;<a class="" data-toggle="collapse"><h4>Hi <?php echo $_SESSION['user_name']?></h4></a><br />
          </li>
          <li style="text-align:center; float:left">
            &nbsp;&nbsp;<a style="padding:20px; margin: 0;" href="login.php">Sign Out</a>
          </li>
        </ul>
      </div>
      
	  <!-- Search Panel -->
  	  <div id="includedSrchPanel" class="cus_row" style="width:100%"></div>
      
    </div>
  </div>
</div>
<div style="height:42px"></div>

<div class="container">
  <h1>View/Edit</h1>
    <form class="form-actions" name="posting" id="posting">
       
        <fieldset>
          <legend><?php if ($_GET['advert_type']=="advert") { echo "Advertisement";} else if ($_GET['advert_type']=="post") {echo "Publication";} ?></legend>
          
          <div class="control-group">
          
              <div style="width:100%;">
                <div class="cus_row" style="width:30%;">
                    <label class="control-label" for="origin">Origin</label>
                    <div class="controls">
                    
                         <input id="origin" type="text" data-provide="typeahead" autocomplete="off" data-items="4" name="origin" data-source='["Colombo 1", "Colombo 2", "Colombo 3", "Colombo 4", "Colombo 5", "Colombo 6", "Colombo 7", "Colombo 8", "Colombo 9", "Colombo 10", "Colombo 11" ,"Colombo 12" ,"Colombo 13" ,"Colombo 14" ,"Colombo 15" ,"Athurugiriya" ,"Attidiya" ,"Battaramulla" ,"Biyagama" ,"Boralesgamuwa" ,"Dehiwala" ,"Galle" ,"Gampaha" ,"Ja-Ela" ,"Jawatta" ,"Jayawardanapura" ,"Kadawatha" ,"Kalalgoda" ,"Kalapaluwawa" ,"Kalubowila" ,"Kandana" ,"Kandy" ,"Katunayaka" ,"Kelaniya" ,"Kiribathgoda" ,"Kirulapone" ,"Kohuwala" ,"Kolonnawa" ,"Kottawa" ,"Kotte" ,"Kurunegala" ,"Mahabage" ,"Maharagama" ,"Malabe" ,"Matara" ,"Moratuwa" ,"Mount Lavinia" ,"Mulleriyawa" ,"Nawala" ,"Negombo" ,"Nugegoda" ,"Panadura" ,"Pannipitiya" ,"Peliyagoda" ,"Pepiliyana" ,"Polgasowita" ,"Ragama" ,"Rajagiriya" ,"Ratmalana" ,"Seeduwa" ,"Thalawatugoda" ,"Union Place" ,"Wattala"]' value="<?php echo mysql_result($result, 0, "origin") ?>">
                    </div>
                </div>
                <div class="cus_row" style="width:70%;">
                    <label class="control-label" for="destination">Destination</label>
                    <div class="controls">
                        <input id="destination" type="text" data-provide="typeahead" autocomplete="off" data-items="4" name="destination" data-source='["Colombo 1", "Colombo 2", "Colombo 3", "Colombo 4", "Colombo 5", "Colombo 6", "Colombo 7", "Colombo 8", "Colombo 9", "Colombo 10", "Colombo 11" ,"Colombo 12" ,"Colombo 13" ,"Colombo 14" ,"Colombo 15" ,"Athurugiriya" ,"Attidiya" ,"Battaramulla" ,"Biyagama" ,"Boralesgamuwa" ,"Dehiwala" ,"Galle" ,"Gampaha" ,"Ja-Ela" ,"Jawatta" ,"Jayawardanapura" ,"Kadawatha" ,"Kalalgoda" ,"Kalapaluwawa" ,"Kalubowila" ,"Kandana" ,"Kandy" ,"Katunayaka" ,"Kelaniya" ,"Kiribathgoda" ,"Kirulapone" ,"Kohuwala" ,"Kolonnawa" ,"Kottawa" ,"Kotte" ,"Kurunegala" ,"Mahabage" ,"Maharagama" ,"Malabe" ,"Matara" ,"Moratuwa" ,"Mount Lavinia" ,"Mulleriyawa" ,"Nawala" ,"Negombo" ,"Nugegoda" ,"Panadura" ,"Pannipitiya" ,"Peliyagoda" ,"Pepiliyana" ,"Polgasowita" ,"Ragama" ,"Rajagiriya" ,"Ratmalana" ,"Seeduwa" ,"Thalawatugoda" ,"Union Place" ,"Wattala"]' value="<?php echo mysql_result($result, 0, "destination") ?>">
                    </div>
                </div> 
              </div>
              
              <div id="route-controls" class="cus_row" style="width:100%; padding-left: 0px;">
              	<div class="alert alert-info"><strong>Note : </strong>Route will be generated based on the directions confirmed at the time of advertising. If directions were not specified, the route will be based on above provided Origin and Destination. Route can be modified by dragging waypoints, and should be confirmed before completing the update process.</div>
              	<div id="div-draw-route" style="float:left;"><button type="button" class="btn" id="draw-route">Show Route On Map</button></div>
                <div id="div-hide-route" style="float:left;"><button type="button" class="btn" id="hide-route">Collapse Route Panel</button></div>
                <div id="div-reset-route" style="float:left;"><button type="button" class="btn" id="reset-route">Reset Route</button></div>
                <div id="div-save-route" style="float:left;"><button type="button" class="btn" id="save-route">Confirm Directions</button></div>
                <div id="div-load-route" style="float:left;"><button type="button" class="btn" id="load-route">Optimize & Load Modified Route</button></div>
              </div>
              
              <div id="drawRoutePanel" style="float:left; width:100%;">
              	<?php include("drawRoute.php"); ?>
              </div>
              
              <input type="hidden" name="advertisement_type" id="advertisement_type" value="<?php echo $_GET['advert_type']?>" /> 
              <input type="hidden" name="advertisement_id" id="advertisement_id" value="<?php echo $_GET['advert_id']?>" /> 
              <input type="hidden" name="email" id="email" value="<?php echo $_SESSION['user_email']?>" /> 
              <input type="hidden" name="route_string" id="route_string" value="<?php echo str_replace("\\", '', mysql_result($result,0,"travel_route")); ?>" /> 
              
              <input type="hidden" name="action_type" id="action_type" /> 
              <div style="width:100%;">
                <div class="cus_row" style="width:30%; padding-top:10px;">
                    <label class="checkbox">
                        <input type="checkbox" id="split_cost" name="split_cost" value="Y" <?php if (mysql_result($result,0,"split_cost")=="Y") { echo "checked";} ?>>
                        Split Cost
                    </label>
                </div>
                <div class="cus_row" style="width:70%; padding-top:10px;">
                    <label class="checkbox">
                        <input type="checkbox" id="take_turns" name="take_turns" value="Y" <?php if (mysql_result($result,0,"take_turns")=="Y") { echo "checked";} ?>>
                        Take Turns
                    </label>	
                </div>
              </div>
              
              <div>
                <div class="cus_row" style="width:100%; padding-top:10px;">
                    <label class="sr-only" for="travel_date">Travel Date</label>

                    <input id="travel_date" name="travel_date" type="text" class="datepicker" style="width:80px;" data-date-format="yyyy-mm-dd" value="<?php if (mysql_result($result, 0, "travel_date")!="0000-00-00") { echo $travelDateFormatted->format('Y-m-d'); } else { echo "";} ?>">
                </div>
              </div>

            <h3 class="cus_row" style="width:100%;">OR</h3>
            
            <div>
                <div class="cus_row" style="width:30%;">
                    <label class="radio"><input type="checkbox" name="daily" id="daily" value="Y" <?php if (mysql_result($result,0,"daily")=="Y") { echo "checked";} ?>>Daily</label>
                    <label class="radio"><input type="checkbox" name="weekly" id="weekly" value="Y" value="Y" <?php if (mysql_result($result,0,"weekly")=="Y") { echo "checked";} ?>>Weekly</label>
                    <label class="radio"><input type="checkbox" name="monthly" id="monthly" value="Y" <?php if (mysql_result($result,0,"monthly")=="Y") { echo "checked";} ?>>Monthly</label> 
                </div>
                <div class="cus_row" style="width:10%;">
                    <label class="checkbox"><input type="checkbox" name="mon" id="mon" name="mon" value="Y" <?php if (mysql_result($result,0,"mon")=="Y") { echo "checked";} ?>>Mon</label>
                    <label class="checkbox"><input type="checkbox" name="tue" id="tue" name="tue" value="Y" <?php if (mysql_result($result,0,"tue")=="Y") { echo "checked";} ?>>Tue</label>
                    <label class="checkbox"><input type="checkbox" name="wed" id="wed" name="wed" value="Y" <?php if (mysql_result($result,0,"wed")=="Y") { echo "checked";} ?>>Wed</label>
                </div>
                <div class="cus_row" style="width:10%;">
                    <label class="checkbox"><input type="checkbox" name="thu" id="thu" name="thu" value="Y" <?php if (mysql_result($result,0,"thu")=="Y") { echo "checked";} ?>>Thu</label>
                    <label class="checkbox"><input type="checkbox" name="fri" id="fri" name="fri" value="Y" <?php if (mysql_result($result,0,"fri")=="Y") { echo "checked";} ?>>Fri</label>
                    <label class="checkbox"><input type="checkbox" name="sat" id="sat" name="sat" value="Y" <?php if (mysql_result($result,0,"sat")=="Y") { echo "checked";} ?>>Sat</label>
                </div>
                <div class="cus_row" style="width:10%;">
                    <label class="checkbox"><input type="checkbox" name="sun" id="sun" name="sun" value="Y" <?php if (mysql_result($result,0,"sun")=="Y") { echo "checked";} ?>>Sun</label>
                </div>
                <div class="cus_row" style="width:40%;">
                    
                </div>
            </div>

            <label class="control-label cus_row"  style="width:100%; padding-top:10px"><strong>Time :</strong></label>
            <div style="width:100%;">
                <div class="cus_row" style="width:30%;">
                    <label class="sr-only" for="origin_time">From Origin</label>
                    <div class="input-append">
                        <input id="origin_time" name="origin_time" type="text" class="input-small" style="width:70px;" value="<?php echo mysql_result($result, 0, "origin_time") ?>">
                        <span class="add-on"><i class="icon-time"></i></span>
                    </div>
                </div>
                <div class="cus_row" style="width:70%;">
                    <label class="sr-only" for="dest_time">From Destination</label>
                    <div class="input-append">
                        <input id="dest_time" name="dest_time" type="text" class="input-small" style="width:70px;" value="<?php echo mysql_result($result, 0, "dest_time") ?>">
                        <span class="add-on"><i class="icon-time"></i></span>
                    </div>
                </div>
              </div>
              <label class="control-label cus_row"  style="width:100%; padding-top:10px"><strong>Average Estimations :</strong></label>
              <div style="width:100%;">
                  <div class="cus_row" style="width:30%;">
                        <label class="sr-only" for="dest_time">Distance (Km)</label>
                        <div class="input-append">
                            <input id="travel_distance" name="travel_distance" type="text" class="distance input-small" style="width:70px;" value="<?php echo mysql_result($result, 0, "travel_distance") ?>" />
                        </div>
                   </div>
                   <div class="cus_row" style="width:70%;">
                    <label class="sr-only" for="travel_duration">Duration (Hrs)</label>
                    <div class="input-append">
                        <input id="travel_duration" name="travel_duration" type="text" class="input-small" style="width:70px;" value="<?php echo mysql_result($result, 0, "travel_time") ?>" />
                    </div>
                </div>
              </div>
              <div>
                <div class="cus_row" style="width:100%; padding-top:10px;">
                    <label class="sr-only" for="price_per_seat">Price per Seat-Trip (Rs.)</label>
                    <input id="price_per_seat" name="price_per_seat" type="text" style="width:80px;" value="<?php echo mysql_result($result, 0, "price") ?>"  />
                </div>
              </div>
              <div style="width:100%;">
                <div class="cus_row" style="width:30%;">
                    <label class="control-label" for="vehicle_type_id">Vehicle Type</label>
                    <div class="controls" style="width:auto">
                        <select id="vehicle_type_id" name="vehicle_type_id" style="width:auto;">
                            <option value="1">Car</option>
                            <option value="2">Van</option>
                            <option value="3">Double Cab</option>
                            <option value="4">Bus</option>
                        </select>
                    </div>
                </div>
                <div class="cus_row" style="width:70%;">
                    <label class="control-label" for="numOfSeats">Number Of Seats</label>
                    <div class="controls">
                        <select id="numOfSeats" name="numOfSeats" style="width:60px;">
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                            <option value="6">6</option>
                            <option value="7">7</option>
                            <option value="8">8</option>
                            <option value="9">9</option>
                            <option value="10">10</option>
                            <option value="11">11</option>
                            <option value="12">12</option>
                            <option value="13">13</option>
                            <option value="14">14</option>
                            <option value="15">15</option>
                            <option value="16">16</option>
                            <option value="17">17</option>
                            <option value="18">18</option>
                            <option value="19">19</option>
                            <option value="20">20</option>
                        </select>
                    </div>
                </div>

                <div class="cus_row" style="width:70%;"> 
                  
                <?php 
                  $sql = " SELECT u.name, u.email, r.* FROM `reservation` r, user u WHERE r.email=u.email and r.advert_id='{$_GET['advert_id']}' "; 

                  $resResult = mysql_query($sql) or trigger_error(mysql_error());
                  $num = mysql_num_rows($resResult);
                  $i = 0;
				  
				  if ($num>0) {
				  	echo "<h3>User Requests</h3>";
				  }

                  for ( $i=0; $i < $num; $i++ ){ ?>
                  
                    <div><a href="user_view.php?user_id=<?php echo mysql_result($resResult,$i,"email"); ?>">
                      <?php echo mysql_result($resResult,$i,"name"); ?></a> 
                          requested <?php echo mysql_result($resResult,$i,"seat_count"); ?> Seats on <?php echo mysql_result($resResult,$i,"updated_on"); ?> 
                          <!-- FIXME: Same customer cannot reserve more seats later-->
						  <?php if (getRemainingSeats(mysql_result($resResult,$i,"reservation_id")) >= mysql_result($resResult,$i,"seat_count")
									and getAcceptedSeats(mysql_result($resResult,$i,"reservation_id")) < mysql_result($resResult,$i,"seat_count")) {?>              
                          	<img class="clsAcceptRes" seatCount="<?php echo mysql_result($resResult,$i,"seat_count"); ?>" usrID="<?php echo mysql_result($resResult,$i,"email"); ?>" resrID="<?php echo mysql_result($resResult,$i,"reservation_id"); ?>" reqRoute="<?php echo str_replace("\\", '', mysql_result($resResult,$i,"desired_route")); ?>" src="resources/icons/accept.png" />
                          <?php } else if (mysql_result($resResult,$i,"seat_count") == getAcceptedSeats(mysql_result($resResult,$i,"reservation_id"))){ ?> <img src="resources/icons/accepted_reservation.png" /> <?php } ?> 
						
                        <?php if (mysql_result($resResult,$i,"desired_route")!="") { ?>
                         <img desRoute="<?php echo str_replace("\\", '', mysql_result($resResult,$i,"desired_route")); ?>" id="<?php echo mysql_result($resResult,$i,"reservation_id"); ?>" class="user-directions-btn img-responsive" src="resources/icons/show_on_map.png" style="width: 40px;"  />
                         <?php } ?>
                    </div>
                  <?php
                  }
                  ?>
                  </div>
              </div>
              
          <div class="form-actions cus_row" style="width:100%; padding-left: 0px;">
            <button type="button" class="btn btn-large btn-primary" id="update-btn">UPDATE</button>
            <button type="button" class="btn btn-large btn-primary" id="complete-btn">COMPLETED</button>
            <button type="button" class="btn btn-large btn-primary" id="delete-btn">DELETE</button>
          </div>
        </fieldset>

    </form>
    
    <!-- Notification Panel -->
  	<div id="includedNotifPanel"></div>
    
    <!-- User Desired Route Map -->
    <div id="div-desired-map-panel" style="position:fixed; top:17%; left:12.5%; width:75%; background-color: lightblue; border-style:double;">
    	<?php include("view_user _directions.php"); ?>
    </div>

  	<!-- Site footer -->
    <div class="navbar navbar-inverse navbar-fixed-bottom">
    	<div class="navbar-inner"> <a class="brand" href="#" style="padding-left:7%">&copy; Carpooling.lk 2013</a> </div>
    </div>
</div>

<!-- JAVASCRIPT INCLUDES -->
<script type="text/javascript" src="resources/js/bootstrap-datepicker.js"></script>
<script type="text/javascript" src="resources/js/bootstrap-modal.js"></script>
<script type="text/javascript" src="resources/js/bootstrap-transition.js"></script>
<script type="text/javascript" src="resources/js/bootstrap-collapse.js"></script>
<script type="text/javascript" src="resources/js/bootstrap-typeahead.js"></script>
<script type="text/javascript" src="resources/js/jquery.timepicker.js"></script>
<script type="text/javascript" src="common/admin.js"></script>

<script type="text/javascript">
	
	//JS Validations
	function isDigit(inputVal)  {
		var pattern = /^\d+(?:\.\d+)?$/;  
		if(pattern.test(inputVal)) {  
			return true;    
		} else {  
			return false;  
		}
	}
	
	var desiredRoute = "";
	var mergedRoute = "";

	$( document ).ready(function() {
    
    $("#update-btn").bind('click', function(){
											
		//JS validations				   
		if(!isDigit($("#travel_distance").val())){
		  alert("Please enter a valid decimal value as distance.");
		  $("#travel_distance").focus();
		} else if(!isDigit($("#travel_duration").val())){
		  alert("Please enter a valid decimal value as duration.");
		  $("#travel_duration").focus();
		} else if(!isDigit($("#price_per_seat").val())){
		  alert("Please enter a valid decimal value as the seat price.");
		  $("#price_per_seat").focus();
		} else {
		  $("#action_type").val("update");
		  $("#route_string").val(tempRoute);
          submitForm();
		}

    });
	
	$("#complete-btn").bind('click', function(){
		$("#action_type").val("complete");
        submitForm();
    });
	
	$("#delete-btn").bind('click', function(){
		$("#action_type").val("delete");
        submitForm();
    })
	
  
    $("#vehicle_type_id").val("<?php echo $vehicle_type; ?>");

    $("#numOfSeats").val("<?php echo $numOfSeats; ?>");

  });
	//Include Search panel
	$(function(){
      $("#includedSrchPanel").load("search_panel.php"); 
    });
	

	$(function() {
			   
		$('#travel_date').datepicker();
    	//$('#travel_date').datepicker( "option", "dateFormat", "yy-mm-dd" );
		
		$('#origin_time').timepicker({ 'scrollDefaultNow': true });
		$('#dest_time').timepicker({ 'scrollDefaultNow': true });
	});
	//Include Notification panel
	$(function(){
      $("#includedNotifPanel").load("notification_panel.php"); 
    });
	
 	function submitForm(){
      jQuery.ajax({
        url: 'updatePosting.php',
        type: "POST",
        data: $('#posting').serialize(),
        success: function(data) {
          if(data=="success"){
            showMsg("Updated.");
			alert("Successfully Updated.");
            location.href="my_posts.php";
          }else if(data=="deleteSuccess") {
		  	showMsg("Deleted.");
			alert("Successfully Deleted.");
            location.href="my_posts.php";
		  }else{  alert(data); }
        }
      });
    }
	
	$(function(){
        $("#drawRoutePanel").hide();
		$("#div-save-route").hide();
		$("#div-load-route").hide();
		$("#div-reset-route").hide();
		$("#div-desired-map-panel").hide();
		$("#div-hide-route").hide();
    });
	
	$("#draw-route").bind('click', function(){
		$("#drawRoutePanel").show();
		orig = $('#origin').val();
		dest = $('#destination').val();
		initialize(orig, dest);
		console.info($('#route_string').val());
		if($('#route_string').val() != ""){
			tempRoute = $('#route_string').val();
			loadSavedRoute();
		}
		$("#div-save-route").show();
		$("#div-draw-route").hide();
		$("#div-reset-route").show();
		$("#div-hide-route").show();
    });
	
	$("#reset-route").bind('click', function(){
		$("#drawRoutePanel").show();
		orig = $('#origin').val();
		dest = $('#destination').val();
		initialize(orig, dest);
		$("#div-save-route").show();
		$("#div-hide-route").show();
    });
	
	$("#save-route").bind('click', function(){
		save_waypoints();
		$("#div-load-route").show();
    });
	
	$("#hide-route").bind('click', function(){
		$("#drawRoutePanel").hide();
		$("#div-save-route").hide();
		$("#div-hide-route").hide();
		$("#div-load-route").hide();
		$("#div-reset-route").show();
    });

	$("#load-route").bind('click', function(){
		$("#drawRoutePanel").show();
		loadSavedRoute();
		$("#div-load-route").hide();
		$("#div-save-route").show();
    });
	
	$(".user-directions-btn").bind('click', function(event){
	  desiredRoute = "";
      desiredRoute = $(this).attr('desRoute');
	  $("#div-desired-map-panel").show();
	  initializeUserMap();
	  loadUserRoute(desiredRoute);
    });
	
	$(".clsAcceptRes").bind('click', function(event){
	
		var advertID = $('#advertisement_id').val();
		var seatCount = $(this).attr('seatCount');
		var usrID = $(this).attr('usrID');
		var resrID = $(this).attr('resrID');
		
		var originalRoute = $('#route_string').val();
		var requestedRoute = $(this).attr('reqRoute');
		
		jQuery.ajax({
			url: 'accept_reservation.php?advert_id='+advertID+'&seat_count='+seatCount+'&email='+usrID+'&res_id='+resrID,
			type: "GET",
			success: function(data) {
			  if(data=="success"){
				alert("Reservation accepted successfully.");
				location.reload();
			  }else {  
				alert("Something went wrong while accepting reservation.."); 
			  }
			}
		});
		
		if (originalRoute != "" && requestedRoute != "") {
			mergeWaypoints(originalRoute, requestedRoute, advertID);
		}

	});

	function mergeWaypoints(originalRoute, requestedRoute, advertID) {
		
		var reqRouteObj = eval('(' + requestedRoute + ')');
		var reqRouteWP = [];
		
		for(var i=0;i<reqRouteObj.waypoints.length;i++){
			reqRouteWP[i] = reqRouteObj.waypoints[i];
		}
		
		var oriRouteObj = eval('(' + originalRoute + ')');
		var oriRouteWP = [];
		var oriRouteWPLength = oriRouteObj.waypoints.length;

		for(var i=0;i<reqRouteWP.length;i++){
			oriRouteObj.waypoints[oriRouteWPLength+i] = reqRouteWP[i];
		}
		 
		mergedRoute = JSON.stringify(oriRouteObj);

		jQuery.ajax({
			url: 'updateMergedRoute.php?advert_id=' + advertID +'&mergedRoute=' + mergedRoute,
			type: "GET",
			success: function(data) {
			  if(data=="success"){
				alert("Routes merged successfully.");
			  }else {  
				alert("Something went wrong while merging routes.."); 
			  }
			}
		});

		//console.log("THE ROUTE : " + JSON.stringify(oriRouteObj));
	}

</script>
</body>
</html>